package com.tinyproxy.common;

import java.io.*;
import java.util.UUID;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * TinyProxy关键配置信息
 *
 * @author catii
 */
public class Cfg {

    private boolean remote;

    private String remoteHost = "127.0.0.1";

    private int remotePort = 13080;

    /**
     * 本地端口固定
     */
    private final int localPort = 10080;

    private String token = UUID.randomUUID().toString().replace("-", "");

    public static Cfg load(File file) throws IOException {
        if (!file.exists() || file.isDirectory()) {
            return null;
        }
        Cfg result = new Cfg();
        try (var reader = new BufferedReader(new FileReader(file, UTF_8))) {
            for (String line; (line = reader.readLine()) != null; ) {
                String s = line.trim();
                int i = s.indexOf("=");
                if (s.isEmpty() || i < 0) {
                    continue;
                }
                String k = s.substring(0, i).trim();
                String v = s.substring(i + 1).trim();
                if ("remote".equalsIgnoreCase(k)) {
                    result.remote = "true".equals(v);
                } else if ("remoteHost".equalsIgnoreCase(k)) {
                    result.remoteHost = v;
                } else if ("remotePort".equalsIgnoreCase(k)) {
                    try {
                        result.remotePort = Integer.parseInt(v);
                    } catch (Exception e) {
                        result.remotePort = 13080;
                    }
                } else if ("token".equalsIgnoreCase(k)) {
                    result.token = v;
                }
            }
        }

        return result;
    }

    public void save(File file) throws IOException {
        file.getParentFile().mkdirs();
        try (var writer = new PrintWriter(new FileWriter(file, UTF_8))) {
            writer.println("remote=" + remote);
            writer.println("remoteHost=" + remoteHost);
            writer.println("remotePort=" + remotePort);
            writer.println("token=" + token);
        }
    }

    public boolean isRemote() {
        return remote;
    }

    public String getRemoteHost() {
        return remoteHost;
    }

    public int getRemotePort() {
        return remotePort;
    }

    public int getLocalPort() {
        return localPort;
    }

    public String getToken() {
        return token;
    }

    @Override
    public String toString() {
        if (remote) {
            return "{ serverPort=" + remotePort +
                    ", token=" + token + " }";
        } else {
            return "{ remote=" + remoteHost + ":" + remotePort +
                    ", sock5 Port=" + localPort +
                    ", token=" + token + " }";
        }
    }

}